package com.longcai.cm.delay;

import lombok.ToString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @author libingxing
 */
@ToString
public class SecKillGoodDelay implements Delayed {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    private final String goodId;

    /**
     * 到期执行时间 单位：分钟
     */
    private final Long timeout;

    public SecKillGoodDelay(String goodId, long timeout) {
        logger.info("商品：" + goodId + "加入秒杀商品计时，计时" + timeout + "秒");
        this.goodId = goodId;
        this.timeout = System.currentTimeMillis() + timeout * 1000;
    }

    public String getGoodId() {
        return goodId;
    }

    @Override
    public int compareTo(Delayed other) {
        return this.timeout.compareTo(((SecKillGoodDelay) other).timeout);
    }

    @Override
    public long getDelay(TimeUnit unit) {
//       返回值 = 初始时间 + 到期时间 - 现在时间
        return unit.convert(timeout - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }


}
